java读取同一文件行上的字符串和整数
您好,我有一个函数,它可以读取由空格(01 0 2 0 1 0 2 0 1 0 1)分隔的int,并在向量中按位置插入位置。 这很好用
public void readTemplate() throws NumberFormatException, IOException {
File templateFile = new File ("C:\\Temp\\templateFile.txt");
FileReader fr = new FileReader(templateFile);
BufferedReader br = new BufferedReader(fr);
String row;
int j=0;
while((row = br.readLine()) != null) {
String[] strings = row.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
vectorTemplate[j] = foo;
j++;
}
}
br.close();
fr.close();
System.out.println("TEMPLATE FILE SUCCESFULY OPENED");
}
现在我有一个新的需求,那就是读取同一行上的字符串
认为这是投注者的名字和他们的赌注:
约翰0 1 2 1 0 1 2 1 0 1 0 0 1 0
我有一个Bet类型的类,在这个类中,我需要将名称保存为String,并将该用户的Bet向量中的其他元素保存为String
我不知道如何将第一个信息作为字符串读取,以保存在变量名中,并将行的其余部分作为向量保存
我尝试过一些替代方案,但我总是遇到java。lang.NumberFormatException
我相信错误在我留下的粗体(totalBets[j].setName(str)强> )
public void betsReads() throws IllegalArgumentException, IOException {
File betsFile = new File ("C:\\Temp\\bets.txt");
FileReader fr = new FileReader(betsFile);
BufferedReader br = new BufferedReader(fr);
for(int j = 0; j < size; j++) {
String row;
while((row= br.readLine()) != null) {
totalBets[j] = new Bet();
String[] strings = row.split(" ");
for (String str : strings) {
**totalBets[j].setName(str);**
for(int i = 0; i < bets.vectorBets.length; i++) {
Integer foo = Integer.parseInt(str);
totalBets[j].vectorBers[i] = foo;
}
j++;
}
}
}
br.close();
fr.close();
# 1 楼答案
令牌数组中的第一个
String
是名称。之后的每一个值都是赌注。另外,使用try-with-Resources
而不是显式关闭。像